package com.fang.distributed_locks.controller;

import com.fang.distributed_locks.utils.LockUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author Bernie_fang
 * @Date 2024/2/19 22:13
 **/
@RequestMapping("/lock")
@RestController
public class LockTestController {

    @Autowired
    private LockUtil lockUtil;

    @GetMapping("/tryLock")
    public String getLock(String id, String value, String msg) {
        boolean lock = lockUtil.lock("LOCK_TEST", value, 2);
        if (!lock) {
            return "id + " + id + " lock fail!";
        }
        try {
            System.out.println("id " + id + ", msg: " + msg);
            Thread.sleep(1800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boolean clearLock = lockUtil.clearLock("LOCK_TEST", value);
            if (clearLock) {
                System.out.println("id: " + id + "成功释放锁");
            }
        }
        return "lock success";
    }


}
